import AjaxTool from './ajaxTool.js'
const {
    ajax
} = AjaxTool


let dateList = document.querySelector('#date-list')
let selected = document.querySelector('#selected')
let isBookWin = document.querySelector('.isBooked')
let bookListDom = document.querySelector('#list')
let comfirmWin = document.querySelector('#comfirm-win')
let comfirmBtn = document.querySelector('#comfirm')
let cancle = document.querySelector('#cancle')
let mask = document.querySelector('#mask')

const baseUrl = 'http://shopback.bluej.cn/api/'
let bookListUrl = `${baseUrl}f_user/chooseday`
let token = localStorage.getItem('token')
let today = new Date()
let year = today.getFullYear()
let month = today.getMonth() + 1
let date = today.getDate()
let openFlag = true
let bookMes = {}
let bookListParams = {
    token,
    day_time: `${year}-${month}-${date}`
}
//渲染 下拉框
function renderDateCom() {
    let oneDay = 24 * 60 * 60 * 1000
    let timestr = today.getTime()
    let timeListStr = ''
    // console.log(year,month,date);
    let selectedStr = `
            ${month}月${date}日
            <div class="arrow" id="arrow"></div>
    `
    selected.innerHTML = selectedStr
    for (let i = 0; i < 7; i++) {
        let tempDay = new Date(timestr + i * oneDay)
        let tempYear = tempDay.getFullYear()
        let tempMonth = tempDay.getMonth() + 1
        let tempDate = tempDay.getDate()
        // console.log(`${tempMonth}-${tempDate}`);
        timeListStr += `
        <li class="date-items" day_time='${tempYear}-${tempMonth}-${tempDate}'>${tempMonth}月${tempDate}日</li>
        `
    }
    dateList.innerHTML = timeListStr
}

//渲染中间预约内容
function renderList(arr) {
    let str = ''
    str = `<div class="loading"></div>`
    bookListDom.innerHTML = str
    setTimeout(() => {
        str = ''   
        arr.forEach(v => {
            let canBook = new Date() - new Date(`${v.day_time}T${v.show_name.slice(0,5)}`) > 0
            // console.log(`${v.day_time} ${v.show_name.slice(0,5)}`);
            // console.log(new Date());
            console.log(canBook)
            str += `
            <div class="items" show_id='${v.show_id}' day_time='${v.day_time}' show_name='${v.show_name}' canBook=${canBook ? 0 : 1}>
                <section>${v.show_name}</section>
                <section style='color:${canBook ? 'red':'black'}'>${canBook ? '不可预约' : '可预约' }</section>
            </div>
            `
        });
        bookListDom.innerHTML = str
    }, 500)

}

//点击改变下拉框显示隐藏并改变箭头方向
selected.addEventListener('click', () => {
    let arrow = document.querySelector('#arrow')
    if (openFlag) {
        dateList.style.display = 'block'
        arrow.classList.add('active')
        openFlag = false
    } else {
        dateList.style.display = 'none'
        arrow.classList.remove('active')
        openFlag = true
    }
})
// 事件委托 
dateList.addEventListener('click', (e) => {
    let target = e.target
    let day_time = target.getAttribute('day_time')
    // console.log(day_time);
    let dateArr = day_time.split('-')
    selected.innerHTML = `
        ${dateArr[1]}月${dateArr[2]}日
        <div class="arrow" id="arrow"></div>
    `
    dateList.style.display = 'none'
    arrow.classList.remove('active')
    openFlag = true
    bookListParams = {
        token,
        day_time: day_time
    }
    ajax('GET', bookListUrl, bookListParams).then(res => {
        let data = JSON.parse(res)
        const {
            msg
        } = data
        if (msg == '操作成功') {
            const {
                list
            } = data.result
            renderList(list)
        }
    })

})


//请求中间内容数据
ajax('GET', bookListUrl, bookListParams).then(res => {
    let data = JSON.parse(res)
    const {
        msg
    } = data
    if (msg == '操作成功') {
        const {
            list
        } = data.result
        // console.log(list);
        renderList(list)
    }
})

//点击内容 委托预约 保存改数据到对象
bookListDom.addEventListener('click', function (e) {
    let target = e.target.parentNode
    let show_id = target.getAttribute('show_id')
    let day_time = target.getAttribute('day_time')
    let show_name = target.getAttribute('show_name')
    let canBook = target.getAttribute('canBook')
    // console.log(show_name);
    if(canBook == 0 ){
        isBookWin.style.display =  'flex'
        mask.style.display = 'block'
        setTimeout(()=>{
            isBookWin.style.display =  'none'
            mask.style.display = 'none'
        },1500)
        return
    }else{
        bookMes = {
            token,
            show_id,
            day_time,
            show_name
        }
        comfirmWin.style.display = 'flex'
        mask.style.display = 'block'
    }

})
// 确认框确定后
comfirmBtn.addEventListener('click', () => {
    let bookUrl = `${baseUrl}f_user/bookday`
    ajax('POST', bookUrl, JSON.stringify(bookMes), 'application/json').then(res => {
        // console.log(res);
        let data = JSON.parse(res)
        const {
            msg
        } = data
        if (msg == '操作成功') {
            const {
                day_time,
                name,
                user_id,
                show_id,
                id
            } = data.result
            localStorage.setItem('bookData', JSON.stringify({
                day_time,
                show_id,
                name,
                user_id,
                id,
                show_name: bookMes.show_name
            }))
            comfirmWin.style.display = 'none'
            mask.style.display = 'none'
            location.href = `./success.html`
        }
    })
})

//确认框取消
cancle.addEventListener('click', () => {
    comfirmWin.style.display = 'none'
    mask.style.display = 'none'
})

renderDateCom()